import axios from 'axios'
import Vue from 'vue';
import { Toast } from 'vant';

Vue.use(Toast);
let sum = 0;
let timer = '';
let toast = '';
// 创建axios实例
const service = axios.create({
  // baseURL:process.env.NODE_ENV == 'development' ? 'http://192.168.1.109:2001' :'',
  timeout: 10000000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    // if(timer){
    //   clearTimeout(timer)
    // }
    // timer = setTimeout(() => {
    //   sum++;
      // toast = Toast.loading({
      //     message: '加载中...',
      //     forbidClick: true,
      //     duration:0
      //   });
      let token = localStorage.getItem('token')
      if (localStorage.getItem('token')) {
        config.headers['token'] = token// 让每个请求携带自定义token 请根据实际情况自行修改
      }
      return config
    // }, 100);
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    // toast.clear();
    if(response.headers.istoken){
      Toast.fail({
        message:'该用户已在其他地方登录',
        onClose:()=>{
            window.location.hash = '/login'
          }
        }
        )
    }
    return response.data
  },
  error => {
    console.log('err' + error) // for debug
    // toast.clear();
    Toast({
        type:'fail',
        message:'网络问题'
    })
    return Promise.reject(error)
  }
)

export default service